<script setup lang="ts">
import { ref, onMounted, reactive, computed, watch } from 'vue'
import { Fold, Expand, Moon, Sunny, Operation } from '@element-plus/icons-vue'
import { useRoute, useRouter } from 'vue-router'
import 'element-plus/theme-chalk/dark/css-vars.css'

const valuesdata = reactive({
  rid: localStorage.getItem('Rid') ?? ''
})

// 面包屑（基于路由 meta.title）
const route = useRoute()
const router = useRouter()
const breadcrumbItems = computed(() => {
  const matched = route.matched || []
  const items = matched
    .filter((m) => (m.meta as any)?.title)
    .map((m) => ({ path: m.path, title: (m.meta as any).title as string }))
  return items.length ? items : [{ path: route.path, title: '页面标题' }]
})

// 侧边栏折叠
const isCollapse = ref(false)
const asideWidth = computed(() => (isCollapse.value ? '64px' : '220px'))
const toggleCollapse = () => {
  isCollapse.value = !isCollapse.value
}

// 全局尺寸密度
const uiSize = ref<'small' | 'default' | 'large'>('default')
const setUiSize = (size: 'small' | 'default' | 'large') => (uiSize.value = size)

// 暗黑模式
const isDark = ref(false)
watch(
  isDark,
  (val) => {
    const cls = document.documentElement.classList
    val ? cls.add('dark') : cls.remove('dark')
    localStorage.setItem('isDark', val ? '1' : '0')
  },
  { immediate: true }
)

// 用户信息
const userName = ref(localStorage.getItem('userName') || localStorage.getItem('currentUser') || '用户')
const userAvatar = computed(() => {
  // 根据用户名生成头像
  const name = userName.value
  const firstChar = name.charAt(0).toUpperCase()
  const colors = [
    '#409eff', '#67c23a', '#e6a23c', '#f56c6c', 
    '#909399', '#9c27b0', '#ff9800', '#795548'
  ]
  const colorIndex = name.charCodeAt(0) % colors.length
  return {
    text: firstChar,
    color: colors[colorIndex]
  }
})

const handleUserCommand = (cmd: string) => {
  if (cmd === 'refresh') {
    router.go(0)
  } else if (cmd === 'logout') {
    router.push('/')
  }
}

onMounted(() => {
  isDark.value = localStorage.getItem('isDark') === '1'
})
</script>

<template>
  <el-config-provider :size="uiSize">
  <el-container style="height: 100vh">
    <!-- 侧边栏 -->
    <el-aside :width="asideWidth"
      style="background: #2d3a4b; color: #fff; display: flex; flex-direction: column; justify-content: space-between; overflow: hidden; transition: width .2s ease;">
      <div>
        <div class="logo-area">
          <div class="logo-dot" />
          <div class="system-title">管理系统</div>
        </div>
        <el-scrollbar height="calc(100vh - 140px)">
          <el-menu :default-active="$route.path" class="el-menu-vertical-demo" background-color="#2d3a4b"
            text-color="#cfd3dc" active-text-color="#fff" router :collapse="isCollapse">
          <el-sub-menu index="0">
            <template #title>工作台</template>
            <el-menu-item :index="`/AddGetStock`">入库管理</el-menu-item>
            <el-menu-item :index="`/AddGetStock`">出库管理</el-menu-item>
            <el-menu-item :index="`/AddDelivery`">入库管理</el-menu-item>
            <el-menu-item :index="`/AddStock`">出库管理</el-menu-item>
            <el-menu-item :index="`/inbound?rid=`+ valuesdata.rid">入库管理</el-menu-item>
            <el-menu-item :index="`/outbound?rid=`+ valuesdata.rid">出库管理</el-menu-item>
          </el-sub-menu>
          <el-sub-menu index="1">
            <template #title>仓库管理</template>
            <el-menu-item :index="`/inbound?rid=`+ valuesdata.rid">入库管理</el-menu-item>
            <el-menu-item :index="`/outbound?rid=`+ valuesdata.rid">出库管理</el-menu-item>
            <el-menu-item index="/ShowAllocation">调拨管理</el-menu-item>
            <el-menu-item index="/Showlosses">报损管理</el-menu-item>
            <el-menu-item index="/ShowInventory">盘点管理</el-menu-item>
          </el-sub-menu>
          <el-sub-menu index="5">
            <template #title>业务管理</template>
            <el-sub-menu index="5-1">
              <template #title>采购管理</template>
              <el-menu-item index="/Purchase">采购列表</el-menu-item>
              <el-menu-item index="/test">新增采购单</el-menu-item>
              <el-menu-item index="/updpurchase">编辑采购单</el-menu-item>
            </el-sub-menu>
            <el-menu-item index="/showPurchaseRefund">采购退货</el-menu-item>
             <el-sub-menu index="5-2">
              <template #title>销售管理</template>
              <el-menu-item index="/showSale">销售列表</el-menu-item>
              <el-menu-item index="/addsale">新增销售单</el-menu-item>
              <el-menu-item index="/updsale">编辑销售单</el-menu-item>
            </el-sub-menu>
            
            <el-menu-item index="/showSaleRefund">销售退货</el-menu-item>
             <el-menu-item index="/getdify">智能客服助手</el-menu-item>
              <el-menu-item index="/ML.NET">智能预测系统</el-menu-item>
             <el-menu-item index="/aaa">数据预处理</el-menu-item>
             <el-menu-item index="/bbb">模型训练</el-menu-item>
             <el-menu-item index="/ccc">出库预测</el-menu-item>
             <el-menu-item index="/ml">ML.NET预测</el-menu-item>
              <el-menu-item index="/enterout-analysis">signalR</el-menu-item>
              <el-menu-item index="/signalr-test">signalR测试</el-menu-item>
            <el-sub-menu index="5-3">
              <template #title>台账</template>
              <el-menu-item index="/getstock">库存</el-menu-item>
              <el-menu-item index="/getenterout">出入库</el-menu-item>
              <el-menu-item index="/getdistribute">库存分布</el-menu-item>
              <el-menu-item index="/getguarantee">保质期</el-menu-item>
              <el-menu-item index="/getwarn">库存预警</el-menu-item>
            </el-sub-menu>
             <el-sub-menu index="5-4">
              <template #title>盘点</template>
              <el-menu-item index="/getcheck">库存盘点</el-menu-item>
              <el-menu-item index="/addcheck">新增盘点</el-menu-item>
               <el-menu-item index="/addprofitloss">新增盘盈盘亏</el-menu-item>
               <el-menu-item index="/getprofitloss">盘盈盘亏</el-menu-item>
            </el-sub-menu>
          </el-sub-menu>
          <el-sub-menu index="7">
            <template #title>财务管理</template>
          <el-menu-item :index="`/ShowFinancialCategory`">财务类别</el-menu-item>
          <el-menu-item :index="`/ShowPayableManagement`">应付管理</el-menu-item>
          <el-menu-item :index="`/ShowReceivablesManagement`">应收管理</el-menu-item>
          <el-menu-item :index="`/ShowFinancialBookkeeping`">财务记账</el-menu-item>
        </el-sub-menu>
          
          <el-sub-menu index="2">
            <template #title>报表管理</template>
            <el-menu-item index="/report/analysis">报表分析</el-menu-item>
          </el-sub-menu>
          <el-sub-menu index="3">
            <template #title>基础资料</template>
            <el-menu-item :index="`/Depot`">仓库管理</el-menu-item>
            <el-menu-item :index="`/Location`">库位管理</el-menu-item>
            <el-menu-item :index="`/Device`">设备管理</el-menu-item>
            <el-menu-item :index="`/Supplier`">供应商管理</el-menu-item>
            <el-menu-item :index="`/Client`">客户管理</el-menu-item>
            <el-menu-item :index="`/Unit`">单位管理</el-menu-item>
            <el-menu-item :index="`/Category`">产品类别</el-menu-item>
            <el-menu-item :index="`/Product`">产品管理</el-menu-item>
            <el-menu-item :index="`/Carrier`">承运商管理</el-menu-item>
             <el-menu-item :index="`/Inventory`">库存盘点</el-menu-item>
             <el-menu-item :index="`/InventoryAdd`">库存盘点新增</el-menu-item>
             <el-menu-item :index="`/Storage`">工单仓库管理</el-menu-item>
             <el-menu-item :index="`/StorageAdd`">工单仓库管理添加</el-menu-item>
             <el-menu-item :index="`/StorageDetail`">工单仓库管理详情</el-menu-item>
          </el-sub-menu>
          <el-sub-menu index="4">
            <template #title>
              <RouterLink :to="'/ShowView?rid=' + valuesdata.rid" style="color: white;">系统设置</RouterLink>
            </template>
            <el-sub-menu index="4-1">
              <template #title>
                <RouterLink :to="`/ShowView?rid=`+ valuesdata.rid" style="color: white;">用户管理</RouterLink>
              </template>

              <el-sub-menu index="4-1-1" style="width: auto;">
                <template #title>
                  <RouterLink :to="`/ProductOutAllowsView?rid=`+ valuesdata.rid" style="color: white;">详情</RouterLink>
                </template>
              </el-sub-menu>
              <el-sub-menu index="4-1-2" style="width: auto;">
                <template #title>
                  <RouterLink :to="`/InventoryAudit?rid=`+ valuesdata.rid" style="color: white;">库存盘点</RouterLink>
                </template>
              </el-sub-menu>
              <el-sub-menu index="4-1-3" style="width: auto;">
                <template #title>
                  <RouterLink :to="`/LedgerManagement?rid=`+ valuesdata.rid" style="color: white;">库存查询</RouterLink>
                </template>
              </el-sub-menu>
              <el-sub-menu index="4-1-4" style="width: auto;">
                <template #title>
                  <RouterLink :to="`/LedAccountManagement?rid=`+ valuesdata.rid" style="color: white;">批次查询</RouterLink>
                </template>
              </el-sub-menu>
              <el-sub-menu index="4-1-5" style="width: auto;">
                <template #title>
                  <RouterLink :to="`/SProductOutAllowsView?rid=`+ valuesdata.rid" style="color: white;">库存预警</RouterLink>
                </template>
              </el-sub-menu>
              <el-sub-menu index="4-1-6" style="width: auto;">
                <template #title>
                  <RouterLink :to="`/SignalRView?rid=`+ valuesdata.rid" style="color: white;">signalr页面</RouterLink>
                </template>
              </el-sub-menu>

            </el-sub-menu>

            <el-sub-menu index="4-2">
              <template #title>
                <RouterLink :to="`/ShowRoleView?rid=`+ valuesdata.rid" style="color: white;">角色管理</RouterLink>
              </template>
            </el-sub-menu>

            <el-sub-menu index="4-3">
              <template #title>
                <RouterLink :to="`/DeapartMent?rid=`+ valuesdata.rid" style="color: white;">部门管理</RouterLink>
              </template>
            </el-sub-menu>

            <el-sub-menu index="4-4">
              <template #title>
                <RouterLink :to="`/ShowResource?rid=`+ valuesdata.rid" style="color: white;">资源管理</RouterLink>
              </template>
            </el-sub-menu>

          </el-sub-menu>
        </el-menu>
        </el-scrollbar>
      </div>
      <!-- 底部消息和退出 -->
      <!-- <div class="sidebar-footer">
        <el-badge :value="50" class="item" style="margin-right: 16px;"><i class="el-icon-bell"></i> 消息</el-badge>
        <el-button type="text" icon="el-icon-switch-button" style="color: #fff;">退出</el-button>
      </div> -->
    </el-aside>
    <!-- 主体 -->
    <el-container>
      <el-header class="main-header">
        <div class="header-left">
          <el-button size="small" @click="toggleCollapse" class="collapse-btn" text>
            <el-icon class="collapse-icon">
              <component :is="isCollapse ? Expand : Fold" />
            </el-icon>
            <span class="collapse-text">{{ isCollapse ? '展开菜单' : '收起菜单' }}</span>
          </el-button>
          <el-breadcrumb separator="/" class="breadcrumb">
            <el-breadcrumb-item v-for="(item, idx) in breadcrumbItems" :key="idx">
              <RouterLink :to="item.path">{{ item.title }}</RouterLink>
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <div class="header-right">
          <el-dropdown trigger="click">
            <span class="link dropdown-trigger">
              <el-icon><Operation /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="setUiSize('small')">紧凑</el-dropdown-item>
                <el-dropdown-item @click="setUiSize('default')">默认</el-dropdown-item>
                <el-dropdown-item @click="setUiSize('large')">宽松</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>

          <el-button text @click="isDark = !isDark" class="link">
            <el-icon>
              <component :is="isDark ? Sunny : Moon" />
            </el-icon>
          </el-button>

          <span class="rid-badge">RID: {{ valuesdata.rid }}</span>
          <el-dropdown @command="handleUserCommand">
            <span class="user-entry">
              <el-avatar 
                size="small" 
                :style="{ marginRight: '6px', background: userAvatar.color }"
              >
                {{ userAvatar.text }}
              </el-avatar>
              <span class="user-name">{{ userName }}</span>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="refresh">刷新</el-dropdown-item>
                <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>
      <el-main class="main-area">
        <el-card class="content-card" shadow="never">
          <router-view />
        </el-card>
      </el-main>
    </el-container>
  </el-container>
  </el-config-provider>
</template>

<style scoped>
.logo-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 24px 0 12px 0;
}

.logo-dot {
  width: 36px;
  height: 36px;
  background: linear-gradient(135deg, #79bbff, #409eff);
  border-radius: 50%;
  margin-bottom: 10px;
  box-shadow: 0 6px 12px rgba(64, 158, 255, .35);
}

.logo {
  width: 80px;
  height: 80px;
  margin-bottom: 8px;
}

.system-title {
  color: #fff;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 16px;
}

.sidebar-footer {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 16px 0;
  border-top: 1px solid #334055;
}

.main-header {
  background: #fff;
  box-shadow: 0 1px 4px rgba(0,21,41,.08);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
}

.page-title {
  margin-left: 8px;
  font-weight: 600;
  color: #303133;
}

.breadcrumb {
  margin-left: 12px;
  color: #606266;
}

.header-right .link {
  margin-left: 12px;
  color: #409eff;
}

.dropdown-trigger {
  display: inline-flex;
  align-items: center;
  font-size: 16px;
}

.header-right .divider {
  margin: 0 8px;
  color: #c0c4cc;
}

.rid-badge {
  display: inline-flex;
  align-items: center;
  height: 24px;
  padding: 0 8px;
  border-radius: 12px;
  background: #ecf5ff;
  color: #409eff;
  font-weight: 600;
  margin-right: 8px;
}

.user-entry {
  display: inline-flex;
  align-items: center;
  cursor: pointer;
}
.user-name { color: #606266; }

.main-area {
  background: #f5f6fa;
}

.content-card {
  min-height: calc(100vh - 120px);
}

.collapse-btn {
  display: inline-flex;
  align-items: center;
  color: #606266;
}
.collapse-btn:hover {
  color: #409eff;
}
.collapse-icon {
  margin-right: 6px;
}
.collapse-text {
  font-weight: 600;
}
</style>